# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

myStartsWith <- function(str, prefix){
    substring(str, 1, nchar(prefix)) == prefix
}

library(optparse)
library(ropls)
library(magrittr)
library(RColorBrewer)
library(scales)
library(tidyverse)

option_list <- list(
make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
make_option("--cp", default = "", type = "character", help = "compare info ")
)
opt <- parse_args(OptionParser(option_list = option_list))

outData <- read_csv(opt$i) %>%
    select(c("Class")) %>%
    group_by(Class) %>%
    summarise(Count = n()) %>%
    mutate(percent = Count * 100 / sum(Count)) %>%
    rowwise() %>%
    do({
        result <- as.data.frame(.)
        percent <- result[1, "percent"]
        class <- result[1, "Class"] %>% as.character()
        newClass <- ifelse(percent < 2, "Others", class)
        result$Class <- newClass
        result
    }) %>%
    group_by(Class) %>%
    summarise_all(sum) %>%
    arrange(desc(percent)) %>%
    mutate(percent = round(percent, 2)) %>%
    rename(`Percentage(%)` = percent)

outData

write_csv(outData, "Class_Count.csv")
